#include "../include/Timer.h"
#include "../base.h"
#include <malloc.h>

struct Timer_st{
	long long timeAt;
	TimerCallBack callBack;
	void *data;
};
typedef struct Timer_st Timer;

static LinkedList *mTimers = NULL;

static Timer* newTimer(long long timeAt,TimerCallBack callBack,void *data){
	Timer* timer = (Timer*)malloc(sizeof(Timer));
	timer->timeAt = timeAt;
	timer->callBack = callBack;
	timer->data = data;
	return timer;
}

//初始化定时器
void _initTimer()
{
	mTimers = newLinkedList();
}

//循环调用定时器
void _loopCallTimer()
{
	if(mTimers==NULL)
		return;
	LinkedList *timers_bk = mTimers;
	mTimers = newLinkedList();
	long long timeNow = currentTimeMillis();
	/////////////////////////////////////
	while(!LinkedList_isEmpty(timers_bk)){
		Timer *timer = LinkedList_removeAt(timers_bk,0);
		if(timeNow>=timer->timeAt){
			timer->callBack(timer->data);
			free(timer);
		}else{
			LinkedList_addLast(mTimers,timer);
		}
	}
	deleteLinkedList(timers_bk);
}

//设置一个定时器任务
//delayMs:延时
//callBack:回调
//data:回调时的参数
void setTimer(long long delayMs,TimerCallBack callBack,void *data)
{
	setTimerAt(currentTimeMillis()+delayMs,callBack,data);
}

//设置一个定时器任务
void setTimerAt(long long atMs,TimerCallBack callBack,void *data)
{
	if(mTimers==NULL)
		return;
	LinkedList_addLast(mTimers,newTimer(atMs,callBack,data));
}

int timerCmp(const void *data1,const void *data2){
	const Timer* thiz  = (const void *)data1;
	const Timer* other = (const void *)data2;
	return thiz->callBack == other->callBack ? 0 : 1;
}

//提前取消定时器回调，如果成功返回data,否则返回NULL
void* unsetTimer(TimerCallBack callBack)
{
	Timer other;
	other.callBack=callBack;
	Timer *timer = (Timer*)LinkedList_remove(mTimers,&other,timerCmp);
	if(timer==NULL){
		return NULL;
	}else{
		void *data = timer->data;
		free(timer);
		return data;
	}
}

